import '../scss/style.scss'
import './style.scss'
import { getSearchHot, getSearchResult, getSearchSuggest } from '../services'
import { $, $all } from '../utils/util'

getSearchHot()
  .then(res => {
    console.log(res.data.result.hots)
    $('.hot ul').innerHTML = res.data.result.hots.map(item => {
      return `<li>${item.first}</li>`
    }).join('')
  })


const show = (name) => {
  $all('.content .list').forEach(item => {
    item.classList.add('hide')
  })
  $(`.${name}`)?.classList.remove('hide')
}

const suggest = async (value) => {
  if (!value) return
  const res = await getSearchSuggest(value)
  console.log(res.data.result.allMatch)
  const allMatch = res.data.result.allMatch || []
  $('.suggest ul').innerHTML = allMatch.map(item => {
    return `<li>${item.keyword}</li>`
  }).join('')
}

const getResult = async (value) => {
  try {
    const res = await getSearchResult(value)
    console.log(res.data.result.songs)
    $('.result').innerHTML = res.data.result.songs.map(item => {
      return `
        <div>${item.name}</div>
      `
    }).join('')
  } catch(e) {
    console.log(e)
  }
}


let timeoutId = null
$('.search_header input').addEventListener('input', e => {
  $('.suggest h3 span').innerHTML = e.target.value
  if (e.target.value.length > 0) {
    show('suggest')
    // 调用搜索建议接口，添加防抖（连续多次调用只执行最后一次）
    if (timeoutId) clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      suggest(e.target.value)
      timeoutId = null
    }, 1000)
  } else {
    show('hot')
  }
})

$('.search_header input').addEventListener('keydown', e => {
  if (e.keyCode === 13) {
    show('result')
    // 调用搜索结果接口
    getResult(e.target.value)
  }
})
